/**
 * @projectName: petJoyHome
 * @author: 小飞
 * @description: TODO
 * @date: 2024/3/1 15:44
 * @version: 1.0
 */
package com.home.exception;

import com.home.result.Result;
import com.home.result.ResultCode;
import com.home.utils.SecurityContextUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.support.DefaultMessageSourceResolvable;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.stream.Collectors;

/**
 * 全局异常处理类
 */
@RestControllerAdvice
@Slf4j
public class BasicExceptionHandler {

    //处理参数异常的方法
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public Result<?> errorHandler(MethodArgumentNotValidException exception) {
        BindingResult bindingResult = exception.getBindingResult();
        String message = bindingResult.getAllErrors().stream().map(DefaultMessageSourceResolvable::getDefaultMessage).collect(Collectors.joining(","));
        return Result.failed(message);
    }

    @ExceptionHandler(BaseException.class)
    public Result<?> errorHandler(BaseException baseException) {
        return Result.failed(baseException.getMessage());
    }

    /**
     * 捕获没有权限的异常
     * @param exception
     * @return
     */
    @ExceptionHandler(AccessDeniedException.class)
    public Result<?> errorHandler(AccessDeniedException exception) {
        String username = SecurityContextUtil.getLoginUser().getUser().getUsername();
        log.info("{}没有访问接口的权限",username);
        return Result.failed(ResultCode.NO_DENATIONALISED.getCode(),ResultCode.NO_DENATIONALISED.getMsg());
    }

    @ExceptionHandler(Exception.class)
    public Result<?> errorHandler(Exception exception) {
        exception.printStackTrace();
        return Result.failed("后台异常,请联系管理员");
    }
}
